package com.gulimall.auth.server.controller;

import com.alibaba.fastjson.TypeReference;
import com.gulimall.auth.server.client.WeiboClient;
import com.gulimall.auth.server.config.WeiboDeveloperConfig;
import com.gulimall.auth.server.feign.MemberFeignService;
import com.gulimall.common.constant.AuthServerConstant;
import com.gulimall.common.vo.MemberRespVo;
import com.gulimall.auth.server.vo.WeiboAccessToken;
import com.gulimall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author djg
 * @date 2020/8/29
 * @des
 */
@Controller
public class OAuth2Controller {

    @Autowired
    private WeiboClient weiboClient;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private WeiboDeveloperConfig weiboDeveloperConfig;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse response) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("client_id", weiboDeveloperConfig.getClientId());
        map.put("client_secret", weiboDeveloperConfig.getClientSecret());
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        //1、根据code换取AccessToken
        WeiboAccessToken accessToken = weiboClient.getAccessToken(map);
        //处理响应数据
        R r = memberFeignService.weiboLogin(accessToken);
        if (r.getCode() == 0) {
            MemberRespVo memberRespVo = r.getData(new TypeReference<MemberRespVo>() {
            });
            //1、解决子域session共享问题，在创建session的时候指定域名
            //TODO 使用spring-session需要解决的两个问题
            //TODO 1、默认发的令牌的session的作用域是当前域名，我们需要扩大他的作用域（auth.gulimall.com->gulimall.com），子域共享session问题
            //TODO 2、使用json来序列化对象到redis中，方便我们观察
            session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVo);
            //2、登陆成功跳转回首页
            System.out.println("登录成功用户信息为" + memberRespVo);
            return "redirect:http://gulimall.com";
        }
        return "redirect:http://auth.gulimall.com/login.html";

    }

}
